# Copyright (C) 2025  Luohao <luohao@100trust.cn>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
from conanbase import ConanBase
from conan.tools.gnu import Autotools, AutotoolsToolchain
from conan.tools.files import copy, chdir
from conan.tools.layout import basic_layout
import os

required_conan_version = ">=2.13.0"

class BusToolsConan(ConanBase):
    description = "The Bus Tools of openUBMC"
    topics = ("conan", "tools", "bus-tools")
    license = "GPL-2.0-or-later"
    settings = "os", "arch", "compiler", "build_type"
    generators = "AutotoolsDeps"
    language = "c"
    homepage = "https://gitcode.com/openUBMC/bus_tools"

    options = {
        "shared": [True, False],
        "fPIC": [True, False]
    }
    default_options = {
        "shared": False,
        "fPIC": True
    }
    
    def configure(self):
        if self.options.shared:
            self.options.rm_safe("fPIC")

    def layout(self):
        basic_layout(self)

    def generate(self):
        # 生成 Autotools 工具链
        tc = AutotoolsToolchain(self)
        env = tc.environment()
        chost = self.buildenv.vars(self).get("CHOST")
        if chost:
            self.output.info(f"Setting CROSS_COMPILE={chost}-")
            env.define("CROSS_COMPILE", f"{chost}-")
        tc.generate(env)

    def build(self):
        with chdir(self, os.path.join(self.source_folder, "src")):
            autotools = Autotools(self)
            autotools.make()

    def package(self):
        copy(self, "i2cdetect", src=os.path.join(self.source_folder, "src/i2c_tools"), dst=os.path.join(self.package_folder, "usr/sbin"))
        copy(self, "i2ctransfer", src=os.path.join(self.source_folder, "src/i2c_tools"), dst=os.path.join(self.package_folder, "usr/sbin"))
        copy(self, "hisportdetect", src=os.path.join(self.source_folder, "src/hisport_tools"), dst=os.path.join(self.package_folder, "usr/sbin"))
        
        # 拷贝权限配置文件
        copy(self, "permissions.ini", src=os.path.join(self.source_folder, "dist"), dst=self.package_folder)
